package org.acghub.demo.akka.chatroom;

import akka.actor.typed.ActorRef;
import akka.actor.typed.ActorSystem;
import akka.actor.typed.Behavior;
import akka.actor.typed.Terminated;
import akka.actor.typed.javadsl.Behaviors;

import java.util.concurrent.TimeUnit;

/**
 * @author zhouhe
 */
public class Main {
    public static Behavior<Void> create() {
        return Behaviors.setup(context -> {
            ActorRef<ChatRoom.RoomCommand> chatRoom = context.spawn(ChatRoom.create(), "chatRoom");
            ActorRef<ChatRoom.SessionEvent> gabbler = context.spawn(Gabbler.create(), "gabbler");
            context.watch(gabbler);
            chatRoom.tell(new ChatRoom.GetSession("ol’ Gabbler", gabbler));

            return Behaviors.receive(Void.class)
                    .onSignal(Terminated.class, sig -> {
                                context.getLog().info("Terminated signal received: {}", sig);
                                return Behaviors.stopped();
                            })
                    .build();
        });
    }

    public static void main(String[] args) {
        ActorSystem<Void> system = ActorSystem.create(Main.create(), "ChatRoomDemo");
        try {
            TimeUnit.SECONDS.sleep(10);
            system.terminate();
            system.log().info("system terminated...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}